package com.xiaohai.controller;

import com.xiaohai.common.R;
import com.xiaohai.exception.CustomException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * ClassName:fileController
 * Package:IntelliJ IDEA
 * Description:
 * Author 何诗海
 *
 * @Create 2024/3/24 12:40
 * @Version 1.0
 */
@RestController
@Slf4j
@RequestMapping("/file")
public class fileController {
    @Value("${file.path}")
    private String path;

    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) throws FileNotFoundException {
        String originalFilename = file.getOriginalFilename();
        log.info("12:{}", originalFilename);
        String path1 = ResourceUtils.getURL("classpath:").getPath() + path;
        File dir = new File(path1);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File imagesFile = new File(dir + "\\/\\" + originalFilename);
//
        try {
            file.transferTo(imagesFile);
        } catch (IOException e) {
            throw new CustomException("文件上传失败");
        }
        return R.success("api/file/" + originalFilename, "上传成功");
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        File imagesFile = new File(path + "\\/\\" + name);
        response.setContentType("image/jpeg");
        try (FileInputStream inputStream = new FileInputStream(imagesFile);
             ServletOutputStream outputStream = response.getOutputStream();) {
            byte[] bytes = new byte[1204];
            int length = 0;
            while ((length = inputStream.read()) != -1) {
                outputStream.write(bytes, 0, length);
            }
        } catch (Exception e) {
            throw new CustomException("文件下载失败！");
        }

    }
}